$(function() {
	
	//验证
	validateInit();
	
	$('#roleTable').bootstrapTable({
		data : getDatas(),
		striped : true, 
		cache : false, 
		pagination : true, 
		sortable : false, 
		toolbar : "#roleToolbar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ], 
		search : true, 
		strictSearch : false,
		showColumns : true, 
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ 
		{
			checkbox:true,
		},
		{
			field : 'roleName',
			title : '角色名'
		}, {
			field : 'roleDesc',
			title : '角色描述'
		}, {
			field : 'createUserName',
			title : '创建人'
		}, {
			field : 'createTime',
			title : '创建时间',
			formatter:function(value,row,index){
				return moment(value).format('YYYY-MM-DD HH:mm:ss');
	    	}
		}, {
			field : 'operate',
			title : '操作'
		}],formatLoadingMessage: function(){
		    return "请稍等，正在加载中。。。";
		}
	});
	
	$("#roleTable").bootstrapTable("hideColumn","id");
});

function validateInit() {

	
	$("#roleForm").validate({
			rules : {
				roleName : {
					required : true,
					remote : {
						url : "../role/roleCheckRepect.action",
						type : "post",
						data : {
							"userId" : function() {
								return $("#addUserForm [name='userId']").val();
							}
						}
					}
				},
				roleDesc: {
					required : true,
					minlength : 5
				}
			},
			messages : {
				roleName : {
					remote : "此角色名称已经存在"
				}
			},
			success : function(label, element) {// error是lavel标签，element是input标签
				labelReset(element);

				var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
				element.parent().append(myTipLabel);
				element.parent().parent().addClass('has-success');
			},
			errorPlacement : function(label, element) {
				labelReset(element);

				var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
								+'<label class="control-label my-tip-label">'
								+	label.text()
								+'</label>';
				element.addClass("error");
				element.parent().append(myTipLabel);
				element.parent().parent().addClass('has-error');
			}
		});
}

function getDatas() {
	var roles;
	$.ajax({
		url: "../role/getAllRoles.action",
		type: "post",
		async: false,//是为了内层ajax在之后访问
		success: function(data) {
			$(data).each(function(){
				//用户id获取用户名
				var userId = this.createUserId;
				var userName = null;
				$.ajax({
					url: "../user/getUserNameById.action",
					type: "post",
					data: {"id":userId},
					async: false,//是为了数据能递出去
					success: function(data) {
						userName = data;
					},
					error: function() {
						toastr.error("获取角色创建人信息出错，请联系管理员");
					}
				});
				
				this.createUserName = userName;
				
				//操作赋值
				this.operate='<button class=\'btn btn-primary btn-xs\' onclick=\'updateRole(' + this.id + ')\'>修改</button>&nbsp;'
						+	 '<button class=\'btn btn-danger btn-xs\' onclick=\'singleDelete('+ this.id + ')\'>删除</button>';
			});
			roles = data;
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
	return roles.reverse();
}

//新增角色
function addRole() {
	formReset("#roleForm");
	$("#addRoleModal").modal("show");	
}

//保存
function saveRoles() {
	if (!$("#roleForm").valid()) {
		return false;
	}
	var datas = $("#roleForm").serialize();
	//console.log(datas);
	$.ajax({
		url: "../role/save.action",
		type: "post",
		data: datas,
		success: function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#roleTable").bootstrapTable("load",getDatas());
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#addRoleModal").modal("hide");
}

//批量删除
function batchDelete() {
	var selectedRoles = $("#roleTable").bootstrapTable('getSelections');
	//console.log(JSON.stringify(selectedRoles)); //Array[Object, Object, ...]
	//return;
	if(selectedRoles.length == 0){
		toastr.error("请勾选你要删除的数据");
		return false;
	}
	var roleIds = new Array();
	$(selectedRoles).each(function(index,role){
		roleIds[index] = role.id;
	})

    deleteCore(roleIds);
    
}

function singleDelete(id) {
	var roleIds=new Array();
	roleIds[0]=id;
	deleteCore(roleIds);
}

function deleteCore(roleIds) {
	swal({
        title: "您确定要删除所选信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "删除",
        closeOnConfirm: false
    }, function () {
    	$.ajax({
    		url: "../role/batchDelete.action",
    		type: "post",
    		data: {"roleIds":roleIds},
    		success: function(data) {
    			if (data.success == "true") {
    				swal("删除成功", "您已经永久删除了所选信息。", "success");
    				$("#roleTable").bootstrapTable("load",getDatas());
    			} else {
    				swal("删除失败", "后台业务处理发生错误，请联系管理员", "error");
    			}
    		},
    		error: function() {
    			swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
    		}
    	});
    });
}

//修改
function updateRole(id) {
	$("#updateRoleForm")[0].reset();
	
	//填充数据
	$.ajax({
		url: "../role/getRoleById.action",
		type: "post",
		data: {"id":id},
		async: false,
		success: function(data) {
			//console.log(data);
			$("#updateRoleModal [name='roleName']").val(data.roleName);
			$("#updateRoleModal [name='roleDesc']").text(data.roleDesc);
			$("#updateRoleModal [name='id']").val(id);
			$("#updateRoleModal").modal("show");
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
}
function updateRoleSave() {
	var role = $("#updateRoleForm").serialize();
	//console.log(role);
	$.ajax({
		url: "../role/update.action",
		type: "post",
		data: role,
		success: function(data) {
			if (data.success == "true") {
				toastr.success("更新成功");
				$("#roleTable").bootstrapTable("load",getDatas());
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#updateRoleModal").modal("hide");
}